<template>
	<div class="app-container">
		<div class="filter-container">
			<el-input
				v-model="listQuery.title"
				placeholder="型号名称"
				style="width: 200px;"
				class="filter-item"
				@keyup.enter.native="handleFilter"
			/>
			<el-select
				v-model="listQuery.importance"
				placeholder="选择品牌"
				clearable
				style="width: 200px"
				class="filter-item"
			>
			<el-option v-for="(item, index) in selectBrandList" :key="index" :label="item.name" :value="item.id" />
			</el-select>
			<el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
				搜索
			</el-button>
			<el-button
				class="filter-item"
				style="margin-left: 10px;"
				type="primary"
				icon="el-icon-edit"
				@click="handleCreate"
			>
				新建
			</el-button>
		</div>

		<el-table
			:key="tableKey"
			v-loading="listLoading"
			:data="list"
			border
			fit
			highlight-current-row
			style="width: 100%;"
			@sort-change="sortChange"
            class="table-margin"
		>
			<el-table-column
				label="编号"
				prop="id"
				sortable="custom"
				align="center"
				width="80"
				:class-name="getSortClass('id')"
			>
				<template slot-scope="{row}">
					<span>{{ row.id }}</span>
				</template>
			</el-table-column>
			<el-table-column label="型号名称" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.name }}</span>
				</template>
			</el-table-column>
            <el-table-column label="扫描方式" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.scanning }}</span>
				</template>
			</el-table-column>
             <el-table-column label="点间距" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.spacing }}</span>
				</template>
			</el-table-column>
             <el-table-column label="单元板分辨率" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.resPower }}</span>
				</template>
			</el-table-column>
             <el-table-column label="单元板尺寸" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.size }}</span>
				</template>
			</el-table-column>
             <el-table-column label="像素密度" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.density }}</span>
				</template>
			</el-table-column>
            <el-table-column label="单元板重量" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.weight }}</span>
				</template>
			</el-table-column>
            <el-table-column label="亮度" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.brightness }}</span>
				</template>
			</el-table-column>
            <el-table-column label="最大电流" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.electric }}</span>
				</template>
			</el-table-column>
            <el-table-column label="最大功耗" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.waste }}</span>
				</template>
			</el-table-column>
            <el-table-column label="最佳视距" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.distance }}</span>
				</template>
			</el-table-column>
            <el-table-column label="灯管类型" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.type }}</span>
				</template>
			</el-table-column>
            <el-table-column label="驱动IC" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.driver }}</span>
				</template>
			</el-table-column>
            <el-table-column label="刷新率" width="110px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.refresh }}</span>
				</template>
			</el-table-column>
            <el-table-column label="其他参数" width="300px" align="center">
				<template slot-scope="{row}">
                    <span v-for="(item, key) in row.otherPara" :key='key'>
                        <span>{{ row.otherPara.length === key+1 ? item : item+',' }}</span>
                    </span>
				</template>
			</el-table-column>
			
			<el-table-column label="操作" align="center" width="200px" class-name="small-padding fixed-width">
				<template slot-scope="{row,$index}">
					<el-button type="primary" size="mini" @click="handleUpdate(row)">
						修改
					</el-button>
					<el-button size="mini" type="danger" @click="handleDelete(row,$index)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total>0"
			:total="total"
			:page.sync="listQuery.page"
			:limit.sync="listQuery.limit"
			@pagination="getList"
		/>

		<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
			<el-form
				ref="dataForm"
				:rules="rules"
				:model="temp"
				label-position="left"
				label-width="70px"
				style="width: 400px; margin-left:50px;"
			>
				<el-form-item label="品牌名称" prop="null">
					<el-input v-model="temp.name" />
				</el-form-item>
                <el-form-item label="扫描方式" prop="null">
					<el-input v-model="temp.scanning" />
				</el-form-item>
                <el-form-item label="点间距" prop="null">
					<el-input v-model="temp.spacing" />
				</el-form-item>
                <el-form-item label="分辨率" prop="null">
					<el-input v-model="temp.resPower" />
				</el-form-item>
                <el-form-item label="尺寸" prop="null">
					<el-input v-model="temp.size" />
				</el-form-item>
                <el-form-item label="像素密度" prop="null">
					<el-input v-model="temp.density" />
				</el-form-item>
                <el-form-item label="重量" prop="null">
					<el-input v-model="temp.weight" />
				</el-form-item>
                <el-form-item label="亮度" prop="null">
					<el-input v-model="temp.brightness" />
				</el-form-item>
                <el-form-item label="最大电流" prop="null">
					<el-input v-model="temp.electric" />
				</el-form-item>
                <el-form-item label="最大功耗" prop="null">
					<el-input v-model="temp.waste" />
				</el-form-item>
                <el-form-item label="最佳视距" prop="null">
					<el-input v-model="temp.distance" />
				</el-form-item>
                <el-form-item label="灯管类型" prop="null">
					<el-input v-model="temp.type" />
				</el-form-item>
                <el-form-item label="驱动IC" prop="null">
					<el-input v-model="temp.driver" />
				</el-form-item>
                <el-form-item label="刷新率" prop="null">
					<el-input v-model="temp.refresh" />
				</el-form-item>

				<el-form-item label="其他参数">
					<el-input
						v-model="temp.otherPara"
						:autosize="{ minRows: 2, maxRows: 4}"
						type="textarea"
						placeholder="请输入其他参数,用英文逗号隔开"
					/>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">
					取消
				</el-button>
				<el-button type="primary" @click="dialogStatus==='create'?handleAddBrand():handleUpdateBrand()">
					提交
				</el-button>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
			<el-table :data="pvData" border fit highlight-current-row style="width: 100%">
				<el-table-column prop="key" label="Channel" />
				<el-table-column prop="pv" label="Pv" />
			</el-table>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
			</span>
		</el-dialog>

        <el-dialog
            title="删除"
            :visible.sync="dialogDelVisble"
            width="30%">
            <span>是否删除该品牌信息?</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogDelVisble = false">取 消</el-button>
                <el-button type="primary" @click="handleDeleteBrand">删除</el-button>
            </span>
        </el-dialog>
	</div>
</template>

<script>
import { getBrandList } from '@/api/brand'
import { getLedModelList, getLedModel, addLedModel, updateLedModel, delLedModel } from '@/api/ledModel'
// import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination


export default {
	name: 'ComplexTable',
	components: { Pagination },
	// directives: { waves },
	filters: {
		statusFilter(status) {
			const statusMap = {
				published: 'success',
				draft: 'info',
				deleted: 'danger'
			}
			return statusMap[status]
		},
		typeFilter(type) {
			return calendarTypeKeyValue[type]
		}
	},
	data() {
		return {
			tableKey: 0,
			list: null,
			total: 0,
			listLoading: true,
			listQuery: {
				page: 1,
				limit: 20,
				importance: undefined,
				title: undefined,
				type: undefined,
				sort: '+id'
			},
			sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
			statusOptions: ['published', 'draft', 'deleted'],
			showReviewer: false,
			temp: {
				id: undefined,
				name: '',
				otherPara: '',
			},
            dialogFormVisible: false,
            dialogDelVisble: false,
			dialogStatus: '',
			textMap: {
				update: '修改品牌',
				create: '新增品牌'
			},
			dialogPvVisible: false,
			pvData: [],
			rules: {
				null: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
			},
            selectBrandList: [],
		}
	},
	created() {
        this.getBrandSelect();
	},
	methods: {
		getList() {
			this.listLoading = true
			getLedModelList(this.selectBrandList[0]).then(response => {
                console.log(response)
				this.list = response.list
				this.total = response.total

				// Just to simulate the time of the request
				setTimeout(() => {
					this.listLoading = false
				}, 1.5 * 1000)
			})
		},
		handleFilter() {
			this.listQuery.page = 1
			this.getList()
		},
		handleModifyStatus(row, status) {
			this.$message({
				message: '操作Success',
				type: 'success'
			})
			row.status = status
		},
		sortChange(data) {
			const { prop, order } = data
			if (prop === 'id') {
				this.sortByID(order)
			}
		},
		sortByID(order) {
			if (order === 'ascending') {
				this.listQuery.sort = '+id'
			} else {
				this.listQuery.sort = '-id'
			}
			this.handleFilter()
		},
		resetTemp() {
			this.temp = {
				id: undefined,
				name: '',
				otherPara: '',
			}
		},
		handleCreate() {
			this.resetTemp()
			this.dialogStatus = 'create'
			this.dialogFormVisible = true
			this.$nextTick(() => {
				this.$refs['dataForm'].clearValidate()
			})
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row)
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
			this.$nextTick(() => {
				this.$refs['dataForm'].clearValidate()
			})
        },
        handleDelete(row, index){
            this.temp.index = index;
            this.temp = Object.assign({}, row)
            this.dialogDelVisble = true
        },
        handleAddBrand() {
            addBrand(this.temp).then(() => {
                this.list.unshift(this.temp)
                this.dialogFormVisible = false
                this.$notify({
                    title: 'Success',
                    message: '新建品牌成功',
                    type: 'success',
                    duration: 2000
                })
            })
        },
		handleUpdateBrand() {
			this.$refs['dataForm'].validate((valid) => {
				if (valid) {
                    const tempData = Object.assign({}, this.temp)
                    tempData.otherPara = tempData.otherPara.toString();
					updateBrand(tempData).then(() => {
						const index = this.list.findIndex(v => v.id === this.temp.id)
						this.list.splice(index, 1, this.temp)
						this.dialogFormVisible = false
						this.$notify({
							title: '成功',
							message: '修改品牌信息成功!',
							type: 'success',
							duration: 2000
						})
					})
				}
			})
		},
		handleDeleteBrand(row) {
            const tempData = Object.assign({}, this.temp)
            this.dialogDelVisble = false
            delBrand(tempData.id).then(() => {
                this.list.splice(tempData.index, 1)
                this.$notify({
                    title: '成功',
                    message: '删除品牌信息成功!',
                    type: 'success',
                    duration: 2000
                })
            })
        },
        getBrandSelect(){
            getBrandList().then(response => {
                console.log(response);
                this.selectBrandList = response.list;
                this.listQuery.importance = this.selectBrandList[0];
                this.getList(this.selectBrandList[0]);
            })
        },
		formatJson(filterVal) {
			return this.list.map(v => filterVal.map(j => {
				if (j === 'timestamp') {
					return parseTime(v[j])
				} else {
					return v[j]
				}
			}))
		},
		getSortClass: function(key) {
			const sort = this.listQuery.sort
			return sort === `+${key}` ? 'ascending' : 'descending'
		}
	}
}
</script>

<style scoped>
.table-margin{
    margin-top: 15px;
}
.el-form-item__label{
    width: 80px !important;
}
.el-form-item__content{
    margin-left: 80px !important;
}
</style>